package com.aqa.concurrent;

import org.junit.Test;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLock {

    @Test
    public void testRw() throws InterruptedException {

        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
        ReentrantReadWriteLock.ReadLock rLock = rwLock.readLock();
        ReentrantReadWriteLock.WriteLock wLock = rwLock.writeLock();

        Thread rThread = new Thread(() -> {
            System.out.println("------------ 读锁 begin ---------------");
            try {
                rLock.lock();
                Thread.sleep(5000);
                rLock.unlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("------------ 读锁 end ---------------");
        }, "读锁线程-1");
        rThread.start();
        Thread rThread2 = new Thread(() -> {
            System.out.println("------------ 读锁 begin ---------------");
            try {
                rLock.lock();
                Thread.sleep(5000);
                rLock.unlock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("------------ 读锁 end ---------------");
        }, "读锁线程-1");
        rThread2.start();

        Thread wThread = new Thread(() -> {
            System.out.println("------------ 写锁 begin ---------------");
            wLock.lock();
            wLock.unlock();
            System.out.println("------------ 写锁 end ---------------");
        }, "读锁线程-1");
        wThread.start();

        Thread.currentThread().join();
    }


}
